class Block {
  constructor(container) {
    this.container = container;
    this.timer = null;
    this.state = false;
    this.speed = 2;
    this.sum = 0;
    this.top = 150;
    this.lastRowChilds = null;
  }
  //开始游戏
  start() {
    let _this = this;
    this.state = true;
    //创建每一行
    for (let i = 0; i < 4; i++) {
      this.createRow();
    }
    //定时器
    this.timer = setInterval(() => {
      _this.move();
      _this.judeg();
    }, 35)
  }

  //创建行的函数
  createRow() {
    let firstChild = this.container.firstChild;
    let rowDiv = document.createElement('div');
    rowDiv.className = 'row';
    let blocks = ['block', 'block', 'block', 'block'];
    let random = Math.floor(Math.random() * 4);
    blocks[random] = 'black';
    //入行
    for (let i = 0; i < 4; i++) {
      let block = document.createElement('div');
      block.className = blocks[i];
      rowDiv.appendChild(block);
    }

    if (firstChild === null) {
      this.container.appendChild(rowDiv);
    } else {
      this.container.insertBefore(rowDiv, firstChild);
    }
  }
  //界面的移动
  move() {
    this.top += this.speed;
    this.container.style.top = this.top + 'px';
  }
  //判断状态
  judeg() {
    let rows = document.getElementsByClassName('row');
    this.lastRowChilds = rows[rows.length - 1];
    if (this.top >= 0) {
      this.createRow();
      this.top = -150;
      this.container.style.top = '-150px';
      for (let i = 0; i < this.lastRowChilds.childNodes.length; i++) {
        if (this.lastRowChilds.childNodes[i].className === 'black') {
          this.gameOver();
        } else if (rows.length === 6) {
          this.container.removeChild(this.lastRowChilds);
        }
      }
    }
    this.flash();
  }
  //显示
  flash() {
    let score = document.getElementById('score');
    score.innerHTML = this.sum;
    let res = document.getElementById('res');
    res.innerHTML = `得分:${this.sum}`;
  }
  //click函数
  click() {
    let _this = this;
    this.container.addEventListener('click', e => {
      let tag = e.target;
      if (tag.className === 'black') {
        _this.sum++;
        _this.speed += 0.2;
        tag.className = 'block';
      } else {
        this.gameOver();
      }
    })
  }
  //gameOver
  gameOver() {
    this.state = false;
    clearInterval(this.timer);
    const end = document.getElementById('end');
    end.style.display = 'block';
  }
  //again
  again() {
    this.timer = null;
    this.state = false;
    this.speed = 2;
    this.sum = 0;
    this.top = -150;
    this.lastRowChilds = null;
    this.container.innerHTML = '';
    this.start();
  }

}